//
//  ReleaseSocialViewController.m
//  ShowYork
//
//  Created by hxh on 2020/9/21.
//  Copyright © 2020 hxh. All rights reserved.
//

#import "DynamicPostViewController.h"
#import "SocialReleaseToolView.h"
#import "ZLPhotoBrowser-Swift.h"

#import "SocialReleaseTextHeaderView.h"
#import "SocialResultItemCell.h"
#import "SocialAddItemCell.h"
#import "SocialVideoItemCell.h"
#import "RNNetworkParam.h"
#import "LFAssetExportSession.h"

#import "HomePageItemModel.h"
#import "SocialSeqModel.h"
#import "SocialReleaseModel.h"
#import "SocialSubTopicModel.h"

#define videoHeight 220
#define videoWidth (videoHeight/4*3)



#define photoWidth (kScreenW - 50 - 16 - 8)/3


@interface DynamicPostViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,SocialAddItemCellDelegate,SocialResultItemCellDelegate,SocialVideoItemCellDelegate,SocialReleaseTextHeaderViewDelegate>
@property (nonatomic,assign)BOOL isVideo;

@property (nonatomic,strong)UICollectionView *collectionView;
@property (nonatomic,strong)SocialReleaseTextHeaderView *headerView;
@property (nonatomic,strong)UIView *line;
@property (nonatomic,strong)NSIndexPath *dragingIndexPath;
/// 目标位置
@property (nonatomic,strong)NSIndexPath *targetIndexPath;

@property (nonatomic,strong)UIImageView *dragingImgView;

@property (nonatomic,strong)UIView *deleteView;

@property (nonatomic,strong)UIButton *confirmBtn;

@property (nonatomic,strong)UIButton *cancelBtn;

@property (nonatomic,copy)NSString *content;

@property (nonatomic,strong)NSMutableArray *urls;

@property (nonatomic,strong)NSMutableArray *postItems;

@property (nonatomic,strong)SocialSubTopicModel *currentTagModel;

@property (nonatomic,strong)UIView *coverView;
@property (nonatomic,strong)UIImageView *coverTagImageVIew;
@property (nonatomic,strong)UIImageView *coverRemoveImageView;

@end

@implementation DynamicPostViewController

- (NSMutableArray *)postItems{
    if (!_postItems) {
        _postItems = [NSMutableArray array];
    }
    return _postItems;
}

- (NSMutableArray *)urls{
    if (!_urls) {
        _urls = [NSMutableArray array];
    }
    return _urls;
}



- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [IQKeyboardManager sharedManager].enable = NO;
    
    [self findHairlineImageViewUnder:self.navigationController.navigationBar].hidden = YES;
    
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].enable = YES;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    
    [self findHairlineImageViewUnder:self.navigationController.navigationBar].hidden = NO;
    
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setUI];
    [self registNote];
}

- (void)setUI{
    
    self.isVideo = NO;
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    self.collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
    self.collectionView.alwaysBounceVertical = YES;
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.view addSubview:self.collectionView];
    
    [self.collectionView registerClass:[SocialResultItemCell class] forCellWithReuseIdentifier:@"SocialResultItemCell"];
    [self.collectionView registerClass:[SocialAddItemCell class] forCellWithReuseIdentifier:@"SocialAddItemCell"];
    [self.collectionView registerClass:[SocialVideoItemCell class] forCellWithReuseIdentifier:@"SocialVideoItemCell"];
    [self.collectionView registerClass:[SocialReleaseTextHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SocialReleaseTextHeaderView"];
    
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressMethod:)];
    [self.collectionView addGestureRecognizer:longPress];
    
    self.dragingImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0,kNavBarHeight,photoWidth,photoWidth)];
    self.dragingImgView.hidden = YES;
    self.dragingImgView.layer.masksToBounds = YES;
    self.dragingImgView.contentMode = UIViewContentModeScaleAspectFill;
    [self.view addSubview:self.dragingImgView];
    
    [[UIApplication sharedApplication].keyWindow addSubview:self.deleteView];
    
    self.cancelBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 44, 44)];
    [self.cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [self.cancelBtn setTitleColor:C102 forState:UIControlStateNormal];
    self.cancelBtn.titleLabel.font = font(17);
    [self.cancelBtn addTarget:self action:@selector(cancelMethod) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.cancelBtn];
    
    self.confirmBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 70, 28)];
    [self.confirmBtn setTitle:@"发布" forState:UIControlStateNormal];
    [self.confirmBtn setTitleColor:RGBA(255, 255, 255, 1) forState:UIControlStateNormal];
    [self.confirmBtn setTitleColor:RGBA(255, 255, 255, 1) forState:UIControlStateSelected];
    [self.confirmBtn setTitleColor:RGBA(255, 255, 255, 1) forState:UIControlStateHighlighted];
    self.confirmBtn.titleLabel.font = font(15);
    self.confirmBtn.backgroundColor = RGBA(224, 224, 224, 1);
    self.confirmBtn.layer.cornerRadius = 14;
    self.confirmBtn.layer.masksToBounds = YES;
    self.confirmBtn.userInteractionEnabled = NO;
//    [self.confirmBtn setBackgroundImage:[UIImage imageNamed:@"social_confirm_tag"] forState:UIControlStateNormal];
    [self.confirmBtn setBackgroundImage:[UIImage imageNamed:@"social_confirm_tag"] forState:UIControlStateHighlighted];
    [self.confirmBtn setBackgroundImage:[UIImage imageNamed:@"social_confirm_tag"] forState:UIControlStateSelected];
    [self.confirmBtn addTarget:self action:@selector(confirmMethod) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.confirmBtn];
    
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
    
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"isFirstReleaseSocial"]boolValue]) {
        if (self.targetTagModel != nil) {
            self.currentTagModel = [[SocialSubTopicModel alloc]init];
            self.currentTagModel.topicName = self.targetTagModel.tagName;
            self.currentTagModel.id = self.targetTagModel.tagId;
        }
    }
    
    if (![[[NSUserDefaults standardUserDefaults]objectForKey:@"isFirstReleaseSocial"]boolValue]) {
        self.coverView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH)];
        self.coverView.backgroundColor = RGBA(0, 0, 0, 0.7);
        [[UIApplication sharedApplication].keyWindow addSubview:self.coverView];
        
        self.coverRemoveImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"common_help_tag"]];
        [self.coverView addSubview:self.coverRemoveImageView];
        [self.coverRemoveImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.coverView).offset(-18);
            make.bottom.equalTo(self.coverView).offset(-(200 + GK_SAVEAREA_BTM));
        }];
        self.coverTagImageVIew = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"social_help_tag"]];
        [self.coverView addSubview:self.coverTagImageVIew];
        [self.coverTagImageVIew mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.coverView).offset(50);
            make.top.equalTo(self.coverView).offset(kNavBarHeight + (IPHONE_X?200:150) + 26 + 16);
        }];
        self.coverRemoveImageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dismissCoverView)];
        [self.coverRemoveImageView addGestureRecognizer:tap];
        
        CGRect rectStatus = [[UIApplication sharedApplication] statusBarFrame];
        NSLog(@"status width - %f", rectStatus.size.width); // 宽度
        NSLog(@"status height - %f", rectStatus.size.height);  // 高度
        
        // 导航栏（navigationbar）
        CGRect rectNav = self.navigationController.navigationBar.frame;
        NSLog(@"nav width - %f", rectNav.size.width); // 宽度
        NSLog(@"nav height - %f", rectNav.size.height);  // 高度
 
        // 第一个路径
        UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0,kScreenW, kScreenH)];
        // 透明path
        UIBezierPath *path2 = [[UIBezierPath bezierPathWithRoundedRect:CGRectMake(16,rectStatus.size.height + rectNav.size.height + (IPHONE_X?200:150) - 6, 70, 26) cornerRadius:13] bezierPathByReversingPath];
        [path appendPath:path2];
        // 绘制透明区域
        CAShapeLayer *shapeLayer = [CAShapeLayer layer];
        shapeLayer.path = path.CGPath;
        [self.coverView.layer setMask:shapeLayer];
    }
    
    self.line = [[UIView alloc]init];
    self.line.backgroundColor = RGBA(240, 240, 240, 1);
    [self.view addSubview:self.line];
    [self.line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(0.5);
        make.top.equalTo(self.view);
    }];
    
    
}

#pragma mark - 移除遮罩
- (void)dismissCoverView{
    [self.coverView removeFromSuperview];
    
    [[NSUserDefaults standardUserDefaults] setObject:@(1) forKey:@"isFirstReleaseSocial"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    if (self.targetTagModel != nil) {
        self.currentTagModel = [[SocialSubTopicModel alloc]init];
        self.currentTagModel.topicName = self.targetTagModel.tagName;
        self.currentTagModel.id = self.targetTagModel.tagId;
        [self.collectionView reloadData];
    }
    
    [self.headerView beginTextView];
}
#pragma mark - 长按手势
-(void)longPressMethod:(UILongPressGestureRecognizer*)gestureRecongnizer{
    
    CGPoint point = [gestureRecongnizer locationInView:self.collectionView];
    switch (gestureRecongnizer.state) {
        case UIGestureRecognizerStateBegan:
            [self dragBegin:point];
            break;
        case UIGestureRecognizerStateChanged:
            [self dragChange:point];
            break;
        case UIGestureRecognizerStateEnded:
            [self dragEnd:point];
            break;
        default:
            break;
    }
}

#pragma mark - 导航栏按钮点击事件
- (void)cancelMethod{

    if (self.postItems.count != 0 || (![self.content isSpaceString] && self.content.length > 0)) {
        
        NSString *att = @"未发布的内容退出将不做保存";
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"确定退出？" message:att preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [alertController dismissViewControllerAnimated:YES completion:nil];

        }];
        
        UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self.view endEditing:YES];
            [alertController dismissViewControllerAnimated:YES completion:nil];
            [self.navigationController popViewControllerAnimated:YES];
        }];
        NSMutableAttributedString *alertControllerMessageStr = [[NSMutableAttributedString alloc] initWithString:att];
        [alertControllerMessageStr addAttribute:NSForegroundColorAttributeName value:C102 range:NSMakeRange(0, att.length)];
        [alertControllerMessageStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:NSMakeRange(0, att.length)];
        [alertController setValue:alertControllerMessageStr forKey:@"attributedMessage"];
        
        [cancelAction setValue:[RPAppManager themColor] forKey:@"titleTextColor"];
        [confirmAction setValue:[RPAppManager themColor] forKey:@"titleTextColor"];
        //往alertViewController上添加alertAction
        [alertController addAction:confirmAction];
        [alertController addAction:cancelAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }else{
        [self.view endEditing:YES];
        [self.navigationController popViewControllerAnimated:YES];
    }
}
- (void)confirmMethod{

    [self.view endEditing:YES];
    
    [SVProgressHUD show];
    
    if (self.postItems.count == 0) {
        [self userPost];
        return;
    }
    SocialReleaseModel *itemModel = self.postItems.firstObject;
    if (itemModel.isVideo) {
        
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = paths.firstObject;
        NSString *myPathDocs = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"mergeSlowMoVideo-%d.MP4",arc4random() % 1000]];
        NSURL *outPath = [NSURL fileURLWithPath:myPathDocs];        
        AVURLAsset *asset = [AVURLAsset assetWithURL:[NSURL fileURLWithPath:itemModel.videoUrl]];
        LFAssetExportSession *encoder = [LFAssetExportSession exportSessionWithAsset:asset preset:LFAssetExportSessionPreset1080P];
        encoder.outputFileType = AVFileTypeMPEG4;
        encoder.outputURL = outPath; // 视频输出路径
        [encoder exportAsynchronouslyWithCompletionHandler:^
           {
               if (encoder.status == AVAssetExportSessionStatusCompleted)
               {
                   NSData *data = [NSData dataWithContentsOfFile:encoder.outputURL.path];
                   RNNetworkParam *param = [[RNNetworkParam alloc]init];
                   param.data = data;
                   param.mimeType = @"video/mp4";
                   param.name = @"file";
                   NSDate *date = [NSDate date];
                   NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
                   formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
                   param.filename =  [NSString stringWithFormat:@"%@.mp4",[formatter stringFromDate:date]];
                   [[RPNetworkExtensionTool sharedTool] uploadWithURLString:kGET_REQUEST_URL(DdupUpload) parameters:nil uploadParam:@[param] success:^(id responseObj) {
                       NSString *url = responseObj[RESPONSE];
                       [self.urls addObject:url];
                       dispatch_async(dispatch_get_main_queue(), ^{
                           [self userPost];
                       });

                   } failure:^(NSError *error) {

                   }];
               }else if (encoder.status == AVAssetExportSessionStatusCancelled){
                   [self updateLoadVideoWithItemModel:itemModel];
               }else{
                   [self updateLoadVideoWithItemModel:itemModel];
               }
           }];
    }else{
        // 占位用
        [self.postItems enumerateObjectsUsingBlock:^(SocialReleaseModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [self.urls addObject:[NSNull null]];
        }];
        dispatch_group_t group = dispatch_group_create();
        [self.postItems enumerateObjectsUsingBlock:^(SocialReleaseModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            dispatch_group_enter(group);
            NSData *fileDate = [self compressQualityWithMaxLength:500.0f * 1024.0f image:obj.image];
            RNNetworkParam *param = [[RNNetworkParam alloc]init];
            param.data = fileDate;
            param.mimeType = @"image/jpg";
            param.name = @"file";
            NSDate *date = [NSDate date];
            NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
            formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
            param.filename =  [NSString stringWithFormat:@"%@.jpg",[formatter stringFromDate:date]];
            [[RPNetworkExtensionTool sharedTool] uploadWithURLString:kGET_REQUEST_URL(DdupUpload) parameters:nil uploadParam:@[param] success:^(id responseObj) {
                NSLog(@"第 %d 张图片上传成功: %@", (int)idx + 1, responseObj);
                @synchronized (responseObj) { // NSMutableArray 是线程不安全的，所以加个同步锁
                    NSString *url = responseObj[RESPONSE];
                    self.urls[idx] = url;
                }
                dispatch_group_leave(group);
                
            } failure:^(NSError *error) {
                NSLog(@"第 %lu 张图片上传失败: %@", idx + 1, error);
                dispatch_group_leave(group);
            }];
        }];
        dispatch_group_notify(group, dispatch_get_main_queue(), ^{
            [self userPost];
        });
    }
}

- (void)updateLoadVideoWithItemModel:(SocialReleaseModel *)itemModel{
    NSData *data = [NSData dataWithContentsOfFile:itemModel.videoUrl];
    RNNetworkParam *param = [[RNNetworkParam alloc]init];
    param.data = data;
    param.mimeType = @"video/mp4";
    param.name = @"file";
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    param.filename =  [NSString stringWithFormat:@"%@.mp4",[formatter stringFromDate:date]];
    [[RPNetworkExtensionTool sharedTool] uploadWithURLString:kGET_REQUEST_URL(DdupUpload) parameters:nil uploadParam:@[param] success:^(id responseObj) {
        NSString *url = responseObj[RESPONSE];
        [self.urls addObject:url];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self userPost];
        });

    } failure:^(NSError *error) {

    }];
}

- (NSData *)compressQualityWithMaxLength:(NSInteger)maxLength image:(UIImage *)img{
   CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(img, compression);
    if (data.length < maxLength) return data;
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(img, compression);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    return data;
}

#pragma mark - 发布动态
- (void)userPost{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    if (self.urls.count != 0) {
        NSMutableArray *seqUrl = [NSMutableArray array];
        [self.urls enumerateObjectsUsingBlock:^(NSObject * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj isKindOfClass:[NSString class]]) {
                SocialSeqModel *model = [[SocialSeqModel alloc]init];
                model.postUrl = (NSString *)obj;
                model.seq = @(idx);
                [seqUrl addObject:[model mj_JSONObject]];
            }
        }];
        param[@"seqUrl"] = seqUrl;
        SocialReleaseModel *asset = self.postItems.firstObject;
        NSNumber *type = asset.isVideo?@3:@2;
        param[@"contentType"] = type;
    }else{
        param[@"contentType"] = @1;
    }
    if (self.content.length != 0) {
        param[@"contentText"] = self.content;
    }
    if (self.currentTagModel.id != nil) {
        param[@"tagId"] = self.currentTagModel.id;
        param[@"tagStr"] = self.currentTagModel.topicName;
    }
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"contentText"] = self.content;
    param[@"md5"] = [RPAppManager md5StrWithApi:UserPost];
    param[@"type"] = @"1";
    [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(UserPost) parames:param success:^(id responseObj) {
        [WHToast showImage:[UIImage imageNamed:@"toast_tag_success"] message:@"发布成功" originY:0 duration:2 finishHandler:nil];
        [MobClick event:@"issus_post_success"];
        
        [self.navigationController popViewControllerAnimated:NO];
    
        // 刷新我的和动态列表页面数据
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateUserInfoList" object:nil];
        
    } failure:^(NSError *error) {
        
        [self.urls removeAllObjects];
        
        [WHToast showErrorWithMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
}

#pragma mark -拖拽开始
-(void)dragBegin:(CGPoint)point{
    
    [self.view endEditing:YES];
    
    if (self.postItems.count == 0) {
        return;
    }
    
    self.dragingImgView.size = CGSizeMake(photoWidth, photoWidth);
    
    if (self.isVideo && self.postItems.count != 0) {
        self.dragingImgView.size = CGSizeMake(videoWidth,videoHeight);
    }
    
    [self showDeleteViewAnimation];
    self.dragingIndexPath = [self getDragingIndexPathWithPoint:point];
    if (!_dragingIndexPath) {return;}
    SocialResultItemCell *dragingCell = (SocialResultItemCell *)[self.collectionView cellForItemAtIndexPath:self.dragingIndexPath];
    dragingCell.hidden = YES;
    //更新被拖拽的item
    self.dragingImgView.hidden = NO;
    self.dragingImgView.center = CGPointMake(point.x, point.y- self.collectionView.contentOffset.y);
    SocialReleaseModel *model = self.postItems[self.dragingIndexPath.row];
    self.dragingImgView.image = model.image;
    [self.dragingImgView setTransform:CGAffineTransformMakeScale(1.1, 1.1)];
}

#pragma mark -正在被拖拽
-(void)dragChange:(CGPoint)point{
    if (!_dragingIndexPath) {return;}
    self.dragingImgView.center = CGPointMake(point.x, point.y- self.collectionView.contentOffset.y);;
    self.targetIndexPath = [self getTargetIndexPathWithPoint:point];
    if (self.dragingIndexPath) {
        if (CGRectGetMaxY(self.dragingImgView.frame) > kScreenH  - 100) {
            [self setDeleteViewDeleteState];
        }else{
            [self setDeleteViewNormalState];
        }
    }
    //与目标cell交换位置
    if (_dragingIndexPath && _targetIndexPath) {
        [self rankImageMutableArr];
        
        [self.collectionView performBatchUpdates:^{
            [self.collectionView moveItemAtIndexPath:_dragingIndexPath toIndexPath:_targetIndexPath];
            _dragingIndexPath = _targetIndexPath;
        } completion:^(BOOL finished) {
            if (self.dragingImgView.hidden && finished) {
                [self.collectionView reloadData];
            }
        }];

    }
}

#pragma mark -拖拽结束
-(void)dragEnd:(CGPoint)point{
    
    [self hiddenDeleteViewAnimation];
    if (!self.dragingIndexPath) {return;}
    if (CGRectGetMaxY(self.dragingImgView.frame) > kScreenH  - 100) {

        self.dragingImgView.hidden = YES;
        [self setDeleteViewNormalState];
        [self.postItems removeObjectAtIndex:self.dragingIndexPath.item];
        SocialResultItemCell *item = (SocialResultItemCell*)[self.collectionView cellForItemAtIndexPath:self.dragingIndexPath];
        item.hidden = NO;
        self.isVideo = self.postItems.count == 0;
        
        [self changeConfirmBtnStatus];
        
        [self.collectionView reloadData];

    }else{
        CGRect endFrame = [self.collectionView cellForItemAtIndexPath:self.dragingIndexPath].frame;
        endFrame.origin.y -= self.collectionView.contentOffset.y;//UIScrollView 及其子类都会相对父View发生偏移
        [self.dragingImgView setTransform:CGAffineTransformMakeScale(1.0, 1.0)];
        SocialResultItemCell *item = (SocialResultItemCell*)[self.collectionView cellForItemAtIndexPath:self.dragingIndexPath];
        [UIView animateWithDuration:0.3 animations:^{
            self.dragingImgView.frame = endFrame;
        }completion:^(BOOL finished) {
            self.dragingImgView.hidden = YES;
            item.hidden = NO;
        }];
    }

}


#pragma mark -更新Cell前 需先更新数据源
-(void)rankImageMutableArr
{
    SocialReleaseModel *itemModel = [self.postItems objectAtIndex:self.dragingIndexPath.row];
    [self.postItems removeObjectAtIndex:self.dragingIndexPath.row];
    [self.postItems insertObject:itemModel atIndex:self.targetIndexPath.row];
    [self changeConfirmBtnStatus];

}

#pragma mark -获取被拖动的Cell的IndexPath
-(NSIndexPath*)getDragingIndexPathWithPoint:(CGPoint)startPoint{
    NSIndexPath* dragIndexPath = nil;
    for (NSIndexPath *indexPath in self.collectionView.indexPathsForVisibleItems) {
        //获取当前点所在的cell  且cell不能是添加图片按钮
        if (CGRectContainsPoint([self.collectionView cellForItemAtIndexPath:indexPath].frame, startPoint)) {
            if (indexPath.row == self.postItems.count) {
                return nil;
            }else{
                dragIndexPath = indexPath;
                return dragIndexPath;
            }
        }
    }
    return dragIndexPath;
}

#pragma mark -获取目标Cell的IndexPath
-(NSIndexPath*)getTargetIndexPathWithPoint:(CGPoint)movePoint{
    NSIndexPath *targetIndexPath = nil;
    for (NSIndexPath *indexPath in self.collectionView.indexPathsForVisibleItems) {
        //获取目标点所在的cell  且cell不能是添加图片按钮 如果是起点cell 也没必要交换
        if ([indexPath isEqual:self.dragingIndexPath]) {continue ;}
        if (CGRectContainsPoint([self.collectionView cellForItemAtIndexPath:indexPath].frame, movePoint) && indexPath.row != self.postItems.count) {
            targetIndexPath = indexPath;
        }
    }
    return targetIndexPath;
}

#pragma mark - 处理通知
- (void)registNote{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateReleaseVideo:) name:@"updateReleaseVideo" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateReleasePhoto:) name:@"updateReleasePhoto" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(popToRootViewControllerByRemoteMessage) name:@"popToRootViewControllerByRemoteMessage" object:nil];

    //监听键盘frame改变
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    //添加键盘消失监听事件
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)keyboardWillShow:(NSNotification *)notification
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        CGRect keyboardBounds = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
        self.collectionView.contentInset = UIEdgeInsetsMake(self.collectionView.contentInset.top, 0, keyboardBounds.size.height + kNavBarHeight, 0);
    });
}
- (void)keyboardWillHide:(NSNotification *)notification
{
    self.collectionView.contentInset = UIEdgeInsetsZero;
}


- (void)updateReleasePhoto:(NSNotification *)note{
    UIImage *newImage = note.userInfo[@"data"];
    self.isVideo = NO;
    SocialReleaseModel *itemModel = [[SocialReleaseModel alloc]init];
    itemModel.isVideo = NO;
    itemModel.image = newImage;
    [self.postItems addObject:itemModel];
    [self.collectionView reloadData];
    [self changeConfirmBtnStatus];
}
- (void)updateReleaseVideo:(NSNotification *)note{
    NSString *videoFile = note.userInfo[@"data"];
    self.isVideo = YES;
    
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:videoFile] options:nil];
    AVAssetImageGenerator *assetGen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetGen.appliesPreferredTrackTransform = YES;
    CMTime time = CMTimeMakeWithSeconds(0.0, 600);
    NSError *error = nil;
    CMTime actualTime;
    CGImageRef image = [assetGen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    UIImage *videoImage = [[UIImage alloc] initWithCGImage:image];
    CGImageRelease(image);
    
    SocialReleaseModel *itemModel = [[SocialReleaseModel alloc]init];
    itemModel.isVideo = YES;
    itemModel.videoUrl = videoFile;
    itemModel.image = videoImage;
    [self.postItems removeAllObjects];
    [self.postItems addObject:itemModel];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.collectionView reloadData];
        [self changeConfirmBtnStatus];
    });
    
    
}
- (void)popToRootViewControllerByRemoteMessage{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)enumerateAssetsInAssetCollection:(PHAssetCollection *)assetCollection original:(BOOL)original
{
  NSLog(@"相簿名:%@", assetCollection.localizedTitle);

  PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
  // 同步获得图片, 只会返回1张图片
  options.synchronous = YES;

  // 获得某个相簿中的所有PHAsset对象
  PHFetchResult<PHAsset *> *assets = [PHAsset fetchAssetsInAssetCollection:assetCollection options:nil];
  for (PHAsset *asset in assets) {
    // 是否要原图
    CGSize size = original ? CGSizeMake(asset.pixelWidth, asset.pixelHeight) : CGSizeZero;

    // 从asset中获得图片
    [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
      NSLog(@"%@", result);
    }];
  }
}


#pragma mark - 相机相册
- (void)takePhotoMethod{
   
    if (![RPAppManager checkVideoPhotoAuthorization]) {
        [self setAuthStatusWithMessage:@"此功能需要您授权本App打开照片\n设置方法: 打开手机设置->隐私->照片"];
        return;
    }

    __weak typeof(self)weakSelf = self;
    NSInteger index = 9 - self.postItems.count;
    [ZLPhotoConfiguration default].maxSelectCount = index;
    [ZLPhotoConfiguration default].allowSelectVideo = true;
    [ZLPhotoConfiguration default].showSelectBtnWhenSingleSelect = true;
    [ZLPhotoConfiguration default].maxSelectVideoDuration = 3600;
    if (self.postItems.count != 0) {
        SocialReleaseModel *model = [self.postItems firstObject];
        if (model.isVideo) {
            [ZLPhotoConfiguration default].maxSelectCount = 1;
        }else{
            [ZLPhotoConfiguration default].allowSelectVideo = false;
        }
    }
    [ZLPhotoConfiguration default].allowSelectImage = true;
    [ZLPhotoConfiguration default].allowMixSelect = false;
    [ZLPhotoConfiguration default].allowEditImage = false;
    [ZLPhotoConfiguration default].allowSelectOriginal = false;
    [ZLPhotoConfiguration default].allowTakePhoto = false;
    [ZLPhotoConfiguration default].allowRecordVideo = false;
    [ZLPhotoConfiguration default].enablePhotoClip = false;
    [ZLPhotoConfiguration default].allowPreviewVideo = false;
    [ZLPhotoConfiguration default].themeColorDeploy.navEmbedTitleViewBgColor = [UIColor clearColor];
    [ZLPhotoConfiguration default].customImageNames = @[@"zl_retake",@"zl_albumSelect",@"zl_downArrow",@"zl_btn_selected",@"zl_btn_unselected",@"zl_video"];
    [ZLPhotoConfiguration default].bottomToolViewBtnBgImageShow = YES;
    [ZLPhotoConfiguration default].botomToolViewBtnBgImageName = @"social_confirm_tag";
    [ZLPhotoConfiguration default].themeColorDeploy.bottomToolViewBtnNormalBgColor = RGBA(245, 75, 100, 1);
    [ZLPhotoConfiguration default].navTitleFont = [UIFont boldSystemFontOfSize:16];
    [ZLPhotoConfiguration default].customLanguageKeyValue_objc = @{@"ok":@"我知道了",@"done":@"完成"};
    [ZLPhotoConfiguration default].showInvalidMask = true;
    [ZLPhotoConfiguration default].enableInvalidClickStatus = true;
    [ZLPhotoConfiguration default].enableCropOneVideo = true;
    [ZLPhotoConfiguration default].enableBottomToolViewCropView = true;
    [ZLPhotoConfiguration default].languageType = ZLLanguageTypeChineseSimplified;
    [ZLPhotoConfiguration default].themeColorDeploy.bottomToolViewBgColor = RGBA(21, 24, 35, 1);
    [ZLPhotoConfiguration default].themeColorDeploy.navBarColor = RGBA(21, 24, 35, 1);
    [ZLPhotoConfiguration default].themeColorDeploy.albumListBgColor = RGBA(29, 31, 43, 1);
    [ZLPhotoConfiguration default].themeColorDeploy.thumbnailBgColor = RGBA(29, 31, 43, 1);
    [ZLPhotoConfiguration default].videoExportType = VideoExportTypeMp4;
    [ZLPhotoConfiguration default].showVideoHud = false;
    [ZLPhotoConfiguration default].previewImageBlock = ^{
        [MobClick event:@"album_image_preview_click"];
    };
    ////            如果allowTakePhoto和allowRecordVideo均为false，则不会显示
    ZLPhotoPreviewSheet *sheet = [[ZLPhotoPreviewSheet alloc]initWithSelectedAssets:@[]];
    sheet.selectImageBlock = ^(NSArray<UIImage *> * _Nonnull images, NSArray<PHAsset *> * _Nonnull assets, BOOL status) {
        // 首先是否是视频 唯一性
        PHAsset *asset = assets.firstObject;
        if (asset.mediaType == PHAssetMediaTypeVideo) {
            SocialReleaseModel *itemModel = [[SocialReleaseModel alloc]init];
            weakSelf.isVideo = YES;
            itemModel.isVideo = YES;
            itemModel.image = images.firstObject;
        
            PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
            options.version = PHVideoRequestOptionsVersionOriginal;
            options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
            options.networkAccessAllowed = YES;
            PHImageManager *manager = [PHImageManager defaultManager];

            
            [manager requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset * _Nullable avAsset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
               if ([avAsset isKindOfClass:[AVComposition class]]) {
                    NSArray *assetResources = [PHAssetResource assetResourcesForAsset:asset];
                    PHAssetResource *resource;
                    for (PHAssetResource *assetRes in assetResources) {
                        if (assetRes.type == PHAssetResourceTypePairedVideo ||
                            assetRes.type == PHAssetResourceTypeVideo) {
                            resource = assetRes;
                        }
                      
                    }
                    NSString * fileName = @"";
                    if (resource.originalFilename) {
                        fileName = resource.originalFilename;
                    }
                    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                    NSString *documentsDirectory = paths.firstObject;
                    NSString *myPathDocs = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"mergeSlowMoVideo-%d.MOV",arc4random() % 1000]];
                    NSURL *url = [NSURL fileURLWithPath:myPathDocs];
                    PHAssetResourceRequestOptions *options = [[PHAssetResourceRequestOptions alloc] init];
                    options.networkAccessAllowed = YES;
                    [[PHAssetResourceManager defaultManager] writeDataForAssetResource:resource toFile:url options:options completionHandler:^(NSError * _Nullable error) {
                        if (error == nil) {
                            dispatch_async(dispatch_get_main_queue(), ^{
                                itemModel.videoUrl = url.path;
                                [weakSelf.postItems addObject:itemModel];
                                [weakSelf.collectionView reloadData];
                                [weakSelf changeConfirmBtnStatus];
                            });
                        }
                    }];
                }else{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        AVURLAsset *urlAsset = (AVURLAsset *)avAsset;
                    
                        if (urlAsset != nil) {
                            itemModel.videoUrl = urlAsset.URL.path;
                            [weakSelf.postItems addObject:itemModel];
                            [weakSelf.collectionView reloadData];
                            [weakSelf changeConfirmBtnStatus];
                        }
                    });
                }
            }];
        }else{
            weakSelf.isVideo = NO;
            
            [images enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                SocialReleaseModel *itemModel = [[SocialReleaseModel alloc]init];
                itemModel.image = obj;
                itemModel.isVideo = NO;
                [weakSelf.postItems addObject:itemModel];
            }];
            [weakSelf.collectionView reloadData];
            [weakSelf changeConfirmBtnStatus];
        }
    };
    [sheet showPhotoLibraryWithSender:self];
}
- (void)takVideoMethod{
    
    if (![RPAppManager checkVideoCameraAuthorization]) {
        [self setAuthStatusWithMessage:@"此功能需要您授权本App打开相机\n设置方法: 打开手机设置->隐私->相机"];
        return;
    }
    if (![RPAppManager checkVideoMicrophoneAudioAuthorization]) {
        [self setAuthStatusWithMessage:@"此功能需要您授权本App打开麦克风\n设置方法: 打开手机设置->隐私->麦克风"];
        return;
    }
    if (![RPAppManager checkVideoPhotoAuthorization]) {
        [self setAuthStatusWithMessage:@"此功能需要您授权本App打开照片\n设置方法: 打开手机设置->隐私->照片"];
        return;
    }
    
    [MGJRouter openURL:@"local://ddup/releaseShotView" withUserInfo:@{@"currentVC":self,@"type":@0,@"isVideo":@(!self.isVideo)} completion:nil];
    
}

- (void)setAuthStatusWithMessage:(NSString *)message{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [alertController dismissViewControllerAnimated:YES completion:nil];
        // 去设置相册权限
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication]canOpenURL:url]) {
            [[UIApplication sharedApplication]openURL:url options:@{} completionHandler:nil];
        }
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [alertController dismissViewControllerAnimated:YES completion:nil];
    }];
    [confirmAction setValue:[RPAppManager themColor] forKey:@"titleTextColor"];
    [cancelAction setValue:[RPAppManager themColor] forKey:@"titleTextColor"];
    //往alertViewController上添加alertAction
    [alertController addAction:cancelAction];
    [alertController addAction:confirmAction];
    [self presentViewController:alertController animated:YES completion:nil];
    
}

#pragma mark - SocialAddItemCellDelegate
- (void)addPhoto{
   
    [self.view endEditing:YES];
    __weak typeof(self)weakSelf = self;
    self.isVideo = self.postItems.count == 0;
    NSNumber *type = self.isVideo?@0:@1;
    SocialReleaseToolView *toolView = [[SocialReleaseToolView alloc]initWithToolType:type completeBlock:^(NSInteger index) {
       
        if (index == 1) {
            [weakSelf takVideoMethod];
        }else if(index == 2){
            [weakSelf takePhotoMethod];
        }else{
            [weakSelf takVideoMethod];
        }
    }];
    [toolView show];
}

#pragma mark - 底部删除 视图
- (UIView *)deleteView{
    if (!_deleteView) {
        _deleteView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenH, kScreenW, 100)];
        _deleteView.backgroundColor = RGBA(213, 43, 41, 0.8);
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = 201809;
        [button setImage:[UIImage imageNamed:@"social_tag_select"] forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:@"social_tag_selected"] forState:UIControlStateSelected];
        [button setTitle:@"拖动到此处删除" forState:UIControlStateNormal];
        [button setTitle:@"松手即可删除" forState:UIControlStateSelected];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:14];
        [button layoutButtonWithEdgeInsetsStyle:TYButtonEdgeInsetsStyleTop imageTitleSpace:30];
        [_deleteView addSubview:button];
        [button sizeToFit];
        CGRect frame = button.frame;
        frame.origin.x = (_deleteView.frame.size.width - frame.size.width) / 2;
        frame.origin.y = (100 - frame.size.height) / 2 + 5;
        button.frame = frame;
        
        [[UIApplication sharedApplication].keyWindow addSubview:_deleteView];
    }
    return _deleteView;
}

- (void)showDeleteViewAnimation{
    self.deleteView.hidden = NO;
    [UIView animateWithDuration:0.25 animations:^{
        self.deleteView.transform = CGAffineTransformTranslate(self.deleteView.transform, 0, -100);

    } completion:^(BOOL finished) {

    }];
}

- (void)hiddenDeleteViewAnimation{
    [UIView animateWithDuration:0.25 animations:^{
        self.deleteView.transform = CGAffineTransformIdentity;
    } completion:^(BOOL finished) {
        
    }];
}

- (void)setDeleteViewDeleteState{
    UIButton *button = (UIButton *)[_deleteView viewWithTag:201809];
    button.selected = YES;
}

- (void)setDeleteViewNormalState{
    UIButton *button = (UIButton *)[_deleteView viewWithTag:201809];
    button.selected = NO;
    
    
}
#pragma mark - collectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (self.postItems.count == 9) {
        return 9;
    }else{
        if (self.isVideo && self.postItems.count != 0) {
            return 1;
        }else{
            return self.postItems.count + 1;
        }
    }
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
   
    if (self.postItems.count == 9) {
        SocialResultItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SocialResultItemCell" forIndexPath:indexPath];
        SocialReleaseModel *model = self.postItems[indexPath.item];
        [cell setItemImage:model.image atIndex:indexPath.item];
        cell.delegate = self;
        return cell;
    }else{
        if (self.isVideo && self.postItems.count != 0) {
            SocialVideoItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SocialVideoItemCell" forIndexPath:indexPath];
            SocialReleaseModel *model = self.postItems.firstObject;
            [cell setVideoImg:model.image];
            cell.delegate = self;
            return cell;
        }else{
            if (indexPath.item == self.postItems.count) {
                SocialAddItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SocialAddItemCell" forIndexPath:indexPath];
                cell.delegate = self;
                return cell;
            }else{
                SocialResultItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SocialResultItemCell" forIndexPath:indexPath];
                SocialReleaseModel *model = self.postItems[indexPath.item];
                [cell setItemImage:model.image atIndex:indexPath.item];
                cell.delegate = self;
                return cell;
            }
        }
    }

}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (kind == UICollectionElementKindSectionHeader) {
        SocialReleaseTextHeaderView * header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"SocialReleaseTextHeaderView" forIndexPath:indexPath];
        self.headerView = header;
        [header setContent:self.content andBindTagModel:self.currentTagModel];
        header.delegate = self;
        return header;
    }
    return nil;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    NSMutableArray *imageArr = [NSMutableArray array];
    [self.postItems enumerateObjectsUsingBlock:^(SocialReleaseModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [imageArr addObject:obj.image];
    }];
    
    __weak typeof(self)weakSelf = self;
    [MGJRouter openURL:@"local://ddup/releasePhotoBrowser" withUserInfo:@{@"navigationVC":self.navigationController,@"dataArray":imageArr,@"index":@(indexPath.item),@"block":^(NSInteger index){
        [weakSelf.postItems removeObjectAtIndex:index];
        [weakSelf.collectionView reloadData];
        [weakSelf changeConfirmBtnStatus];
    },} completion:nil];
}


#pragma mark - layoutDelegate
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isVideo && self.postItems.count != 0) {
        return CGSizeMake(videoWidth,videoHeight);
    }
    return CGSizeMake(photoWidth,photoWidth);
}


- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    if (self.isVideo && self.postItems.count != 0) {
        return UIEdgeInsetsMake(28, 16, 0, 0);
    }
    return UIEdgeInsetsMake(28, 16, 0, 50);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 4.0f;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 4.0f;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(kScreenW,IPHONE_X?230:180);
}
#pragma mark - SocialVideoItemCellDelegate
- (void)showVideo{
    __weak typeof(self)weakSelf = self;
    SocialReleaseModel *model = self.postItems.firstObject;
    [MGJRouter openURL:@"local://ddup/releaseVideoBrowser" withUserInfo:@{@"navigationVC":self.navigationController,@"url":model.videoUrl,@"block":^(void){
        [weakSelf.postItems removeAllObjects];
        [weakSelf.collectionView reloadData];
        [weakSelf changeConfirmBtnStatus];
    },} completion:nil];
    
}
#pragma mark - SocialReleaseTextHeaderViewDelegate
- (void)getReleaseText:(NSString *)content{
    self.content = content;
    [self changeConfirmBtnStatus];
}
- (void)showReleaseTagList{
    
    NSString *selectTagName = self.currentTagModel.topicName;
    
    __weak typeof(self)weakSelf = self;
    [MGJRouter openURL:@"local://ddup/releaseTagList" withUserInfo:@{@"navigationVC":self.navigationController,@"tag":selectTagName.length == 0?@"":selectTagName,@"block":^(SocialSubTopicModel *itemModel){
        weakSelf.currentTagModel = itemModel;
        [weakSelf.collectionView reloadData];
    },} completion:nil];
}
- (void)deleteCurrentTag{
    self.currentTagModel = nil;
    [self.collectionView reloadData];
}
#pragma mark - 改变按钮状态
- (void)changeConfirmBtnStatus{

    if ((self.content.length == 0 || [self.content isSpaceString]) && self.postItems.count == 0) {
        self.confirmBtn.userInteractionEnabled = NO;
        self.confirmBtn.selected = NO;
    }else{
        self.confirmBtn.userInteractionEnabled = YES;
        self.confirmBtn.selected = YES;
    }
}

- (UIImageView *)findHairlineImageViewUnder:(UIView *)view
{
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0)
    {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}

#pragma mark - dealloc
- (void)dealloc{
    
}

@end
